package com.tzkyzj.tiremanagersystem.ui;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.tzkyzj.tiremanagersystem.R;
import com.tzkyzj.tiremanagersystem.api.TireApiService;
import com.tzkyzj.tiremanagersystem.api.UserApiService;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserManagementActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private ProgressBar progressBar;
    private UserApiService userApiService;
    private com.tzkyzj.tiremanagersystem.adapter.UserAdapter userAdapter;
    private TextView tvEmptyState;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_management);

        setTitle("用户管理");

        // 先检查Token有效性
        if (!checkTokenValidity()) {
            return;
        }

        // 然后初始化视图
        initViews();

        // 然后检查权限
        if (!checkUserPermission()) {
            return;
        }

        setupRetrofit();
        loadUsers();
    }

    /**
     * 检查Token有效性
     */
    private boolean checkTokenValidity() {
        SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
        String token = prefs.getString("token", "");
        String username = prefs.getString("username", "");

        Log.d("UserManagement", "=== Token有效性检查 ===");
        Log.d("UserManagement", "用户名: " + username);
        Log.d("UserManagement", "Token是否为空: " + token.isEmpty());

        if (token.isEmpty()) {
            Log.e("UserManagement", "Token为空，需要重新登录");
            showTokenExpiredDialog("未检测到登录信息，请重新登录");
            return false;
        }

        // 这里可以添加更多的Token格式检查
        // 例如检查Token是否包含必要的部分等

        Log.d("UserManagement", "Token有效性检查通过");
        return true;
    }

    private void showTokenExpiredDialog(String message) {
        new AlertDialog.Builder(this)
                .setTitle("登录状态异常")
                .setMessage(message)
                .setPositiveButton("重新登录", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        redirectToLogin();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                })
                .setCancelable(false)
                .show();
    }

    /**
     * 检查用户权限
     * @return true: 有权限, false: 无权限
     */
    private boolean checkUserPermission() {
        SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
        String role = prefs.getString("role", "");
        String token = prefs.getString("token", "");
        String username = prefs.getString("username", "");

        Log.d("UserManagement", "=== 权限检查 ===");
        Log.d("UserManagement", "用户名: " + username);
        Log.d("UserManagement", "角色: " + role);
        Log.d("UserManagement", "Token是否为空: " + token.isEmpty());
        Log.d("UserManagement", "===================");

        // 检查Token是否存在
        if (token.isEmpty()) {
            Toast.makeText(this, "未检测到登录信息，请重新登录", Toast.LENGTH_LONG).show();
            redirectToLogin();
            return false;
        }

        // 检查角色权限
        if (!"ADMIN".equals(role)) {
            Toast.makeText(this, "权限不足，只有管理员可以访问用户管理", Toast.LENGTH_LONG).show();
            finish(); // 直接结束当前Activity，不跳转到登录页
            return false;
        }

        return true;
    }

    private void initViews() {
        recyclerView = findViewById(R.id.recycler_view);
        progressBar = findViewById(R.id.progress_bar);
        tvEmptyState = findViewById(R.id.tv_empty_state);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        userAdapter = new com.tzkyzj.tiremanagersystem.adapter.UserAdapter(new ArrayList<>(), new com.tzkyzj.tiremanagersystem.adapter.UserAdapter.OnUserActionListener() {
            @Override
            public void onUserStatusChanged(Long userId, boolean enabled) {
                updateUserStatus(userId, enabled);
            }

            @Override
            public void onEditUser(Long userId, Map<String, Object> user) {
                showEditUserDialog(userId, user);
            }

            @Override
            public void onDeleteUser(Long userId, String username) {
                deleteUser(userId, username);
            }
        });

        recyclerView.setAdapter(userAdapter);
        updateEmptyState();
    }

    private void setupRetrofit() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        // 获取token
        SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
        final String token = prefs.getString("token", "");

        Log.d("UserManagement", "=== Token详细调试 ===");
        Log.d("UserManagement", "Token长度: " + token.length());
        Log.d("UserManagement", "Token内容: " + token);
        Log.d("UserManagement", "===================");

        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .addInterceptor(chain -> {
                    Request original = chain.request();

                    Log.d("UserManagement", "发送请求到: " + original.url());
                    Log.d("UserManagement", "Authorization头: " + token);

                    Request.Builder requestBuilder = original.newBuilder()
                            .header("Authorization", token)
                            .method(original.method(), original.body());

                    Request request = requestBuilder.build();
                    return chain.proceed(request);
                })
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://120.55.37.146:8080/")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        userApiService = retrofit.create(UserApiService.class);
    }
    private void loadUsers() {
        progressBar.setVisibility(View.VISIBLE);
        tvEmptyState.setVisibility(View.GONE);
        recyclerView.setVisibility(View.GONE);

        Call<List<Map<String, Object>>> call = userApiService.getAllUsers();
        call.enqueue(new Callback<List<Map<String, Object>>>() {
            @Override
            public void onResponse(Call<List<Map<String, Object>>> call, Response<List<Map<String, Object>>> response) {
                progressBar.setVisibility(View.GONE);

                if (response.isSuccessful() && response.body() != null) {
                    List<Map<String, Object>> users = response.body();
                    Log.d("UserManagement", "成功加载用户数据，数量: " + users.size());
                    updateUserList(users);
                } else {
                    int statusCode = response.code();
                    Log.e("UserManagement", "加载用户列表失败，状态码: " + statusCode);

                    if (statusCode == 401) {
                        // Token无效或过期
                        Log.e("UserManagement", "Token无效或过期");
                        handleTokenExpired(); // 调用新的处理方法
                    } else if (statusCode == 403) {
                        // 权限不足
                        Log.e("UserManagement", "权限不足，无法访问用户列表");
                        Toast.makeText(UserManagementActivity.this,
                                "权限不足，无法访问用户管理功能", Toast.LENGTH_LONG).show();
                        finish();
                    } else {
                        // 其他错误
                        Log.e("UserManagement", "其他错误: " + statusCode);
                        Toast.makeText(UserManagementActivity.this,
                                "加载用户列表失败: " + statusCode, Toast.LENGTH_SHORT).show();
                        updateEmptyState();
                    }
                }
            }

            @Override
            public void onFailure(Call<List<Map<String, Object>>> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                Log.e("UserManagement", "网络连接失败: " + t.getMessage(), t);
                Toast.makeText(UserManagementActivity.this,
                        "网络连接失败: " + t.getMessage(), Toast.LENGTH_LONG).show();
                updateEmptyState();
            }
        });
    }

    // 专门处理Token过期的情况
    private void handleTokenExpired() {
        Log.d("UserManagement", "处理Token过期");

        // 保存标志，以便登录后返回用户管理页面
        SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean("should_return_to_user_management", true);
        editor.apply();

        // 显示友好的提示
        new AlertDialog.Builder(this)
                .setTitle("会话过期")
                .setMessage("为了保障账户安全，您的登录会话已过期。需要重新登录以继续使用用户管理功能。")
                .setPositiveButton("重新登录", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        redirectToLogin();
                    }
                })
                .setNegativeButton("稍后再说", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish(); // 返回轮胎列表页面
                    }
                })
                .setCancelable(false)
                .show();
    }
    // 处理未授权错误
    private void handleUnauthorizedError() {
        Toast.makeText(this, "登录已过期，请重新登录", Toast.LENGTH_LONG).show();

        // 清除登录状态
        SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.clear();
        editor.apply();

        // 跳转到登录页面
        redirectToLogin();
    }

    // 跳转到登录页面
    private void redirectToLogin() {
        // 清除登录状态
        SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.clear();
        editor.apply();

        Log.d("UserManagement", "清除登录状态，跳转到登录页");

        Intent intent = new Intent(this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }

    // 增强 updateUserList 方法
    private void updateUserList(List<Map<String, Object>> users) {
        Log.d("UserManagement", "更新用户列表，用户数量: " + users.size());

        if (users != null && !users.isEmpty()) {
            // 打印用户数据用于调试
            for (Map<String, Object> user : users) {
                Log.d("UserManagement", "用户数据: " + user.toString());
            }

            userAdapter.updateData(users);
            updateEmptyState();
        } else {
            Log.d("UserManagement", "用户列表为空");
            updateEmptyState();
        }
    }

    // 修改 updateEmptyState 方法
    private void updateEmptyState() {
        if (userAdapter == null || userAdapter.getItemCount() == 0) {
            tvEmptyState.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
            Log.d("UserManagement", "显示空状态");
        } else {
            tvEmptyState.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);
            Log.d("UserManagement", "显示用户列表，项目数: " + userAdapter.getItemCount());
        }
    }

    private void updateUserStatus(Long userId, boolean enabled) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("enabled", enabled);

        Call<Map<String, Object>> call = userApiService.updateUser(userId, requestBody);
        call.enqueue(new Callback<Map<String, Object>>() {
            @Override
            public void onResponse(Call<Map<String, Object>> call, Response<Map<String, Object>> response) {
                if (response.isSuccessful()) {
                    Toast.makeText(UserManagementActivity.this, "用户状态更新成功", Toast.LENGTH_SHORT).show();
                    loadUsers();
                } else {
                    Toast.makeText(UserManagementActivity.this, "更新失败", Toast.LENGTH_SHORT).show();
                    loadUsers();
                }
            }

            @Override
            public void onFailure(Call<Map<String, Object>> call, Throwable t) {
                Toast.makeText(UserManagementActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                loadUsers();
            }
        });
    }

    private void deleteUser(Long userId, String username) {
        new AlertDialog.Builder(this)
                .setTitle("确认删除")
                .setMessage("确定要删除用户 \"" + username + "\" 吗？此操作不可恢复。")
                .setPositiveButton("删除", (dialog, which) -> {
                    performDeleteUser(userId);
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void performDeleteUser(Long userId) {
        Call<Map<String, Object>> call = userApiService.deleteUser(userId);
        call.enqueue(new Callback<Map<String, Object>>() {
            @Override
            public void onResponse(Call<Map<String, Object>> call, Response<Map<String, Object>> response) {
                if (response.isSuccessful()) {
                    Toast.makeText(UserManagementActivity.this, "用户删除成功", Toast.LENGTH_SHORT).show();
                    loadUsers();
                } else {
                    Toast.makeText(UserManagementActivity.this, "删除失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Map<String, Object>> call, Throwable t) {
                Toast.makeText(UserManagementActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void showEditUserDialog(Long userId, Map<String, Object> user) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("编辑用户");

        View dialogView = getLayoutInflater().inflate(R.layout.dialog_edit_user, null);
        builder.setView(dialogView);

        TextInputEditText etUsername = dialogView.findViewById(R.id.et_username);
        TextInputEditText etRole = dialogView.findViewById(R.id.et_role);
        TextInputEditText etPassword = dialogView.findViewById(R.id.et_password);
        TextInputEditText etConfirmPassword = dialogView.findViewById(R.id.et_confirm_password);
        TextInputEditText etTransportCompany = dialogView.findViewById(R.id.et_transport_company);
        TextInputEditText etVehiclePlate = dialogView.findViewById(R.id.et_vehicle_plate);
        TextInputLayout layoutTransportCompany = dialogView.findViewById(R.id.layout_transport_company);
        TextInputLayout layoutVehiclePlate = dialogView.findViewById(R.id.layout_vehicle_plate);
        Switch switchEnabled = dialogView.findViewById(R.id.switch_enabled);
        TextView tvError = dialogView.findViewById(R.id.tv_error);

        populateUserData(user, etUsername, etRole, etTransportCompany, etVehiclePlate, switchEnabled, layoutTransportCompany, layoutVehiclePlate);

        builder.setPositiveButton("保存", null);
        builder.setNegativeButton("取消", (dialog, which) -> dialog.dismiss());

        AlertDialog dialog = builder.create();

        dialog.setOnShowListener(dialogInterface -> {
            Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
            positiveButton.setOnClickListener(v -> {
                if (validateForm(etPassword, etConfirmPassword, tvError)) {
                    updateUser(userId, etPassword.getText().toString(),
                            etTransportCompany.getText().toString(),
                            etVehiclePlate.getText().toString(),
                            switchEnabled.isChecked(), dialog);
                }
            });
        });

        dialog.show();
    }

    private void populateUserData(Map<String, Object> user,
                                  TextInputEditText etUsername,
                                  TextInputEditText etRole,
                                  TextInputEditText etTransportCompany,
                                  TextInputEditText etVehiclePlate,
                                  Switch switchEnabled,
                                  TextInputLayout layoutTransportCompany,
                                  TextInputLayout layoutVehiclePlate) {

        String username = (String) user.get("username");
        etUsername.setText(username != null ? username : "");

        String role = getRoleDisplayName(user.get("role"));
        etRole.setText(role != null ? role : "");

        String transportCompany = (String) user.get("transportCompany");
        etTransportCompany.setText(transportCompany != null ? transportCompany : "");

        String vehiclePlate = (String) user.get("vehiclePlateNumber");
        etVehiclePlate.setText(vehiclePlate != null ? vehiclePlate : "");

        Boolean enabled = getBooleanValue(user.get("enabled"));
        switchEnabled.setChecked(enabled != null && enabled);

        String roleValue = getRoleValue(user.get("role"));
        if ("ADMIN".equals(roleValue)) {
            layoutTransportCompany.setVisibility(View.GONE);
            layoutVehiclePlate.setVisibility(View.GONE);
        } else if ("COMPANY".equals(roleValue)) {
            layoutTransportCompany.setVisibility(View.VISIBLE);
            layoutVehiclePlate.setVisibility(View.GONE);
        } else {
            layoutTransportCompany.setVisibility(View.VISIBLE);
            layoutVehiclePlate.setVisibility(View.VISIBLE);
        }
    }

    private boolean validateForm(TextInputEditText etPassword,
                                 TextInputEditText etConfirmPassword,
                                 TextView tvError) {

        String password = etPassword.getText().toString().trim();
        String confirmPassword = etConfirmPassword.getText().toString().trim();

        if (!password.isEmpty()) {
            if (password.length() < 6) {
                showError(tvError, "密码长度不能少于6位");
                return false;
            }

            if (!password.equals(confirmPassword)) {
                showError(tvError, "两次输入的密码不一致");
                return false;
            }
        }

        hideError(tvError);
        return true;
    }

    private void updateUser(Long userId, String password, String transportCompany,
                            String vehiclePlate, boolean enabled, AlertDialog dialog) {

        ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("保存中...");
        progressDialog.setCancelable(false);
        progressDialog.show();

        Map<String, Object> requestBody = new HashMap<>();

        if (!password.isEmpty()) {
            requestBody.put("password", password);
        }

        requestBody.put("transportCompany", transportCompany.isEmpty() ? null : transportCompany);
        requestBody.put("vehiclePlateNumber", vehiclePlate.isEmpty() ? null : vehiclePlate);
        requestBody.put("enabled", enabled);

        Call<Map<String, Object>> call = userApiService.updateUser(userId, requestBody);
        call.enqueue(new Callback<Map<String, Object>>() {
            @Override
            public void onResponse(Call<Map<String, Object>> call, Response<Map<String, Object>> response) {
                progressDialog.dismiss();

                if (response.isSuccessful()) {
                    Toast.makeText(UserManagementActivity.this, "用户信息更新成功", Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                    loadUsers();
                } else {
                    String errorMessage = "更新失败";
                    try {
                        if (response.errorBody() != null) {
                            String errorBody = response.errorBody().string();
                            if (errorBody.contains("message")) {
                                errorMessage = "更新失败: " + errorBody;
                            }
                        }
                    } catch (Exception e) {
                        Log.e("UserManagement", "Error parsing error body", e);
                    }
                    Toast.makeText(UserManagementActivity.this, errorMessage, Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<Map<String, Object>> call, Throwable t) {
                progressDialog.dismiss();
                Toast.makeText(UserManagementActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_LONG).show();
                Log.e("UserManagement", "Update user failed", t);
            }
        });
    }

    private String getRoleDisplayName(Object roleObj) {
        if (roleObj == null) return "未知角色";

        String role;
        if (roleObj instanceof Map) {
            role = (String) ((Map) roleObj).get("name");
        } else {
            role = roleObj.toString();
        }

        switch (role) {
            case "ADMIN": return "管理员";
            case "COMPANY": return "运输公司";
            case "DRIVER": return "司机";
            default: return role;
        }
    }

    private String getRoleValue(Object roleObj) {
        if (roleObj == null) return null;

        if (roleObj instanceof Map) {
            return (String) ((Map) roleObj).get("name");
        } else {
            return roleObj.toString();
        }
    }

    private Boolean getBooleanValue(Object value) {
        if (value instanceof Boolean) {
            return (Boolean) value;
        } else if (value instanceof String) {
            return Boolean.parseBoolean((String) value);
        }
        return null;
    }

    private void showError(TextView tvError, String message) {
        tvError.setText(message);
        tvError.setVisibility(View.VISIBLE);
    }

    private void hideError(TextView tvError) {
        tvError.setVisibility(View.GONE);
    }


    // 在 UserManagementActivity 类中添加以下方法
    private void refreshTokenAndRetry() {
        Log.d("UserManagement", "尝试刷新Token并重试");

        SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
        String username = prefs.getString("username", "");
        String password = prefs.getString("password", ""); // 注意：不建议存储密码，这里只是临时方案

        if (username.isEmpty() || password.isEmpty()) {
            // 如果没有保存的凭据，只能让用户重新登录
            showTokenExpiredDialog();
            return;
        }

        // 显示刷新提示
        Toast.makeText(this, "正在刷新登录状态...", Toast.LENGTH_SHORT).show();

        // 调用登录API刷新Token
        performTokenRefresh(username, password);
    }

    private void performTokenRefresh(String username, String password) {
        // 创建临时的API服务用于刷新Token
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://120.55.37.146:8080/")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        TireApiService tempApiService = retrofit.create(TireApiService.class);

        Map<String, String> loginRequest = new HashMap<>();
        loginRequest.put("username", username);
        loginRequest.put("password", password);

        Call<Map<String, Object>> call = tempApiService.login(loginRequest);
        call.enqueue(new Callback<Map<String, Object>>() {
            @Override
            public void onResponse(Call<Map<String, Object>> call, Response<Map<String, Object>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    Map<String, Object> loginResponse = response.body();
                    String newToken = (String) loginResponse.get("token");

                    if (newToken != null && !newToken.isEmpty()) {
                        // 保存新的Token
                        SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
                        SharedPreferences.Editor editor = prefs.edit();
                        editor.putString("token", newToken);
                        editor.apply();

                        Log.d("UserManagement", "Token刷新成功，重新加载用户列表");
                        Toast.makeText(UserManagementActivity.this, "登录状态已更新", Toast.LENGTH_SHORT).show();

                        // 重新加载用户列表
                        loadUsers();
                    } else {
                        Log.e("UserManagement", "Token刷新失败：响应中没有Token");
                        showTokenExpiredDialog();
                    }
                } else {
                    Log.e("UserManagement", "Token刷新失败，状态码: " + response.code());
                    showTokenExpiredDialog();
                }
            }

            @Override
            public void onFailure(Call<Map<String, Object>> call, Throwable t) {
                Log.e("UserManagement", "Token刷新网络错误: " + t.getMessage());
                showTokenExpiredDialog();
            }
        });
    }

    private void showTokenExpiredDialog() {
        new AlertDialog.Builder(this)
                .setTitle("登录过期")
                .setMessage("您的登录已过期，需要重新登录")
                .setPositiveButton("重新登录", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        redirectToLogin();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish(); // 返回上一页
                    }
                })
                .setCancelable(false)
                .show();
    }
}